import {createApp} from './main'
import airbnb from './db'//引入数据库和对象仓库

const {app,router,store} = createApp()
if((window as any).__INITIAL_STATE__){
    store.replaceState((window as any).__INITIAL_STATE__)
}
router.beforeEach((to,from,next)=>{
    airbnb.airbnbDB.openStore({
        ...airbnb.languageObjectStore,//通过es6的扩展运算符拿到对象上的一些属性
        ...airbnb.userObjectStore,
        ...airbnb.orderObjectStore,
        ...airbnb.recordObjectStore,
    }).then((res:any)=>{
        console.log('初始化所有对象仓库',res)
        localStorage.getItem('userId')&& store.commit('setUserStatus',1)
        next()
    })
})
router.isReady().then(()=>{//在路由激活之后 执行asyncData异步捕获完数据之后 再在客户端以激活的方式再挂载app实例 接管来自服务端渲染好的html页面
    router.beforeResolve((to,from,next)=>{
        const toComponents = router.resolve(to).matched.flatMap(record =>
            Object.values(record.components)     //比较这两个组件数组 获取差异化的组件数组
        )
        const fromComponents = router.resolve(from).matched.flatMap(record =>
            Object.values(record.components)
        )
        const actived = toComponents.filter((c,i)=>{
            return fromComponents[i]!==c //如果没有存在差异化的组件 则actived.length为0
        })
        if(!actived.length){//没有存在差异化的组件 即刷新当前页面时to和from是一样的 直接执行路由跳转 并且终止数据预取
           return next()
        }
        console.log('开始loading.....')
        Promise.all(actived.map((Component:any) => {
            if (Component.asyncData) {
                return Component.asyncData({
                    store,
                    route: router.currentRoute
                })
            }
        })).then(()=>{
            console.log('结束loading.....')
            next()
       })
})
    app.mount('#app')
})
router.afterEach((to,from,next)=>{
    const {roomDetail} = store.state
    const {title:roomTitle="",owner} = roomDetail||{}
    const {introduce=""} = owner||{}
    const {meta} = to//state.route通过to来拿到
    const {title,keywords,description} = meta
    document.title = `${title}${roomTitle}`
    const keywordsMeta = document.querySelector('meta[name="keywords"]')
    keywordsMeta?.setAttribute("content",`${keywords}${introduce}`)
    const descriptionMeta = document.querySelector('meta[name="description"]')
    descriptionMeta?.setAttribute("content",`${description}${introduce}`)
})